<style lang="less" rel="stylesheet/less" type="text/less">
.api-views {
  padding-top: 20px;
  width: 100%;
  padding-left: 20px;
  min-width: 1186px;
  height: 100%;
}
.row-page {
  margin-top: 20px;
  padding-bottom: 20px;
}
.ivu-modal-body {
  font-size: 16px;
  .ivu-form-item-label {
    font-size: 16px;
  }
}
.ivu-table .user-locked td {
  background-color: lightgoldenrodyellow;
}

.ivu-table .admin-locked td {
  background-color: darkgray;
}
</style>

<template>
  <div class="api-views">
    <div v-if="isCreate">
      <Create @APICreate="APICreate" @back="toIndex()" ref="Reset" />
    </div>
    <div v-else>
      <admin-search-form @search="confirmSearch" @create="toCreate" />
      <Table
        :columns="titleName"
        :data="data"
        :loading="table_loading"
        :row-class-name="apikeyColor"
        :height="tableHeight()"
      />

      <!-- 分页组件 -->
      <Row type="flex" class="row-page" justify="center">
        <Page
          :total="apiTotal"
          :current="page_info.page"
          :page-size="page_info.per_page"
          :page-size-opts="[10,30,50]"
          placement="top"
          show-sizer
          show-total
          @on-change="pageChange"
          @on-page-size-change="perPageChange"
        />
      </Row>
      <Modal v-model="show_modal" title="APIKEY详情和激活" @on-cancel="hide_Modal">
        <EDIT v-if="show_modal" :apikeys_detail="apikeys_detail" @update="activeAPI" />

        <div slot="footer" />
      </Modal>
      <Modal v-model="show_permission" title="APIKEY权限管理" @on-cancel="hide_Modal">
        <Permission
          v-if="show_permission"
          :permission_detail="permission_detail"
          :Perdata="dataList"
          @update="activeAPI"
          @updatePermission="updatePermission"
        />
        <div slot="footer" />
      </Modal>
    </div>
  </div>
</template>
<script>
import qs from "qs";
import adminSearchForm from "./admin-search-form";
import { deleteEmptyValue } from "../../../utils";
import EDIT from "./edit.vue";
import { Button } from "iview";
import Permission from "./permission.vue";
import Create from "./create";
import { computedTableHeight } from "../../../computedTableHeight";

export default {
  mixins: [computedTableHeight],
  components: {
    adminSearchForm,
    EDIT,
    Permission,
    Create
  },
  data() {
    return {
      // logsList: [],
      table_loading: false,
      isCreate: false,
      apikeys_detail: {},
      dataList: [],
      show_permission: false,
      permission_detail: {},
      apiTotal: null,
      PermissionId: null,
      // is_showCreate: false,
      // is_showLook: false,
      // logsPages: null,
      token: "",
      // requestId: null,
      show_modal: false,
      page_info: {
        // 分页信息
        page: 1,
        per_page: 10
      },
      search_info: {
        page: 1,
        per_page: 10
      },

      titleName: [
        {
          title: "序号",
          width: "100px",
          render: (h, { row }) => {
            const index = <div>{row._index + 1}</div>;
            return index;
          }
        },
        {
          title: "用户",
          width: "200px",
          render: (h, { row }) => (
            <div>
              <div>手机:{row.customer.phone}</div>
              <div>名称:{row.customer.name}</div>
            </div>
          )
        },
        {
          title: "apikey_id",
          width: "100px",
          key: "id"
        },
        {
          width: "120px",
          title: "apikey_name",
          key: "name"
        },
        {
          title: "apikey状态",
          width: "120px",
          key: "status"
        },
        {
          title: "资费类型",
          width: "90px",
          render: (h, { row }) => {
            let showType;
            if (row.type === 0) {
              showType = <div>测试</div>;
            } else if (row.type === 1) {
              showType = <div>按次计费</div>;
            } else if (row.type === 2) {
              showType = <div>按时间段计费</div>;
            } else if (row.type === 3) {
              showType = <div>永久授权</div>;
            }
            return showType;
          }
        },
        {
          title: "创建时间",
          width: "160px",
          render: (h, { row }) => {
            this.$moment.locale(navigator.language);
            let real_startTime = this.$moment
              .utc(`${row.created_at}`)
              .local()
              .format("lll");
            return <div>{real_startTime}</div>;
          }
        },
        {
          title: "操作",
          //   width: "300px",
          render: (h, { row }) => {
            let operating;
            if (row.type === 0) {
              operating = (
                <div>
                  <Button
                    name="index__edit"
                    size="small"
                    style="margin-left: 51px"
                    onClick={() => {
                      this.lockAPI(row.id);
                    }}
                    type="warning"
                  >
                    锁定
                  </Button>
                  <Button
                    name="index__delete"
                    size="small"
                    style="margin-left: 8px"
                    onClick={() => {
                      this.editAPI(row);
                    }}
                    type="success"
                  >
                    激活
                  </Button>
                </div>
              );
            } else if (row.type === 1) {
              operating = (
                <div>
                  <Button
                    name="index__delete"
                    size="small"
                    onClick={() => {
                      this.deleteAPI(row.id);
                    }}
                    type="error"
                  >
                    删除
                  </Button>
                  <Button
                    name="index__lock"
                    size="small"
                    style="margin-left:10px"
                    onClick={() => {
                      this.lockAPI(row.id);
                    }}
                    type="warning"
                  >
                    锁定
                  </Button>
                  <Button
                    name="index__active"
                    size="small"
                    style="margin-left: 8px"
                    onClick={() => {
                      this.editAPI(row);
                    }}
                    type="success"
                  >
                    激活
                  </Button>
                </div>
              );
            } else {
              operating = (
                <div>
                  <Button
                    name="index__delete"
                    size="small"
                    onClick={() => {
                      this.deleteAPI(row.id);
                    }}
                    type="error"
                  >
                    删除
                  </Button>
                  <Button
                    name="index__lock"
                    size="small"
                    style="margin-left:10px"
                    onClick={() => {
                      this.lockAPI(row.id);
                    }}
                    type="warning"
                  >
                    锁定
                  </Button>
                  <Button
                    name="index__active"
                    size="small"
                    style="margin-left: 8px"
                    onClick={() => {
                      this.editAPI(row);
                    }}
                    type="success"
                  >
                    激活
                  </Button>
                  <Button
                    name="index__permission"
                    size="small"
                    style="margin-left: 8px"
                    onClick={() => {
                      this.permissionAPI(row);
                    }}
                    type="info"
                  >
                    权限管理
                  </Button>
                </div>
              );
            }

            return operating;
          }
        }
      ],
      data: [] // 列表渲染的数据
    };
  },
  created() {
    this.token = sessionStorage.getItem("token");

    this.APILIST(this.page_info);
  },
  methods: {
    /**
     * 根据apikey状态改变颜色
     *
     */
    apikeyColor(row, index) {
      if (row.status === "user-locked") {
        return "user-locked";
      } else if (row.status === "admin-locked" || row.status === "unactive") {
        return "admin-locked";
      }
    },

    // 确认搜索方法
    confirmSearch({ user, apikey_id, apikey_name, status }) {
      this.page_info.name = user || "";

      this.page_info.apikey_id = apikey_id || "";

      this.page_info.apikey_name = apikey_name || "";

      this.page_info.status = status || "";

      this.page_info = deleteEmptyValue(this.page_info);

      this.search_info = JSON.parse(JSON.stringify(this.page_info));

      this.APILIST(this.page_info);
    },

    /**
     * 页码改变
     * @param  {string} page {当前页码}
     * @return {undefined}
     */
    pageChange(page) {
      this.search_info.page = page;
      this.search_info.per_page = this.page_info.per_page;
      this.APILIST(this.search_info);
    },

    /**
     * 每页显示数改变
     * @param  {string} size {当前每页显示数}
     * @return {undefined}
     */
    perPageChange(size) {
      this.search_info.per_page = size;
      this.page_info.per_page = size;
      this.APILIST(this.page_info);
    },

    deleteAPI(id) {
      this.$Modal.confirm({
        title: "温馨提示", // '温馨提示',
        content: "删除之后将无法恢复，确定吗?", // '删除之后将无法恢复，确定吗？',
        onOk: () => {
          this.table_loading = true;
          let query_str = {
            apikey_id: id,
            token: this.token,
            _method: "DELETE"
          };
          this.axios
            .post(
              `${window.location.origin}/admin/api/v1/admin/apikey/delete`,
              qs.stringify(query_str)
            )
            .then(({ data }) => {
              if (data.code === 200) {
                this.APILIST(this.search_info);
                this.$Message.success("删除成功!");
              } else if (data.code === 7003) {
                this.$Message.error({
                  content: "token验证失败,过期或token错误,请重新登录",
                  duration: 5,
                  closable: true
                });
                this.$router.push({
                  path: "/admin-login"
                });
              } else {
                throw new Error(data.error);
              }
            })
            .catch(err => {
              this.table_loading = false;
              this.$Message.error({
                content: err.message || err.statusText,
                duration: 5,
                closable: true
              });
            });
        },
        onCancel: () => {}
      });
    },
    // api-key列表
    APILIST(param) {
      param.token = this.token;
      const query_str = qs.stringify(param);
      this.table_loading = true;
      this.axios
        .post(`${window.location.origin}/admin/api/v1/admin/apikeys`, query_str)
        .then(({ data }) => {
          if (data.code === 200) {
            this.data = data.apikeys.data;
            this.apiTotal = data.apikeys.total;
          } else if (data.code === 7003) {
            this.$Message.error({
              content: "token验证失败,过期或token错误,请重新登录",
              duration: 5,
              closable: true
            });
            this.$router.push({
              path: "/admin-login"
            });
          } else {
            throw new Error(data.error);
          }
        })
        .catch(err => {
          this.$Message.error({
            content: err.message || err.statusText,
            duration: 5,
            closable: true
          });
        })
        .then(() => {
          this.table_loading = false;
        });
    },

    // 请求点击激活时的详细内容
    editAPI(detail) {
      this.apikeys_detail = detail;
      this.show_modal = true;
    },

    hide_Modal() {
      this.apikeys_detail = null;
    },

    // 激活apikey
    activeAPI(param) {
      let new_param = {
        apikey_id: param.id,
        status: "normal",
        token: this.token,
        _method: "PUT"
      };

      if (param.started_at && param.ended_at) {
        new_param.start_time = param.started_at;
        new_param.end_time = param.ended_at;
      }
      new_param = qs.stringify(new_param);
      this.table_loading = true;
      this.show_modal = false;
      this.axios
        .post(
          `${window.location.origin}/admin/api/v1/admin/update_apikeys_status`,
          new_param
        )
        .then(({ data }) => {
          if (data.code === 200) {
            this.$Message.success("激活状态成功!");
            this.APILIST(this.page_info);
          } else {
            throw new Error(data.error);
          }
        })
        .catch(err => {
          this.table_loading = false;
          this.$Message.error({
            content: err.message || err.statusText,
            duration: 5,
            closable: true
          });
        });
    },

    hide_permission() {
      this.permission_detail = null;
    },

    // 锁定apikey
    lockAPI(id) {
      this.table_loading = true;
      this.axios
        .post(
          `${window.location.origin}/admin/api/v1/admin/update_apikeys_status`,
          {
            apikey_id: id,
            status: "admin-locked",
            token: this.token,
            _method: "PUT"
          }
        )
        .then(({ data }) => {
          if (data.code === 200) {
            this.$Message.success("锁定状态成功!");
            this.APILIST(this.page_info);
          } else {
            throw new Error(data.error);
          }
        })
        .catch(err => {
          this.table_loading = false;
          this.$Message.error({
            content: err.message || err.statusText,
            duration: 5,
            closable: true
          });
        });
      // .then(() => {
      //   this.table_loading = false;
      // });
    },

    /**
     * 权限管理
     */
    permissionAPI(detail) {
      this.permission_detail = detail;

      this.APIPERMISSIONLIST(detail.id);
    },

    /**
     * 打开新建apikey页面
     */
    toCreate() {
      this.isCreate = true;
    },

    /**
     * 创建apikey的方法
     */
    APICreate(param) {
      let query_str = {
        token: this.token,
        area: param.area_code,
        phone: param.phone,
        name: param.name,
        description: param.description
      };
      if (param.type === "永久授权") {
        query_str.type = 3;
      } else if (param.type === "按时间计费") {
        query_str.type = 2;
        query_str.start_time = param.start_time;
        query_str.end_time = param.end_time;
      }

      this.axios
        .post(
          `${window.location.origin}/admin/api/v1/admin/apikey/create`,
          qs.stringify(query_str)
        )
        .then(({ data }) => {
          if (data.code === 200) {
            this.$Message.success("创建成功");
            this.$refs.Reset.handleReset();
          } else if (data.code === 7003) {
            this.$Message.error({
              content: "token验证失败,过期或token错误,请重新登录",
              duration: 5,
              closable: true
            });
            this.$router.push({
              path: "/login"
            });
          } else {
            throw new Error(data.error);
          }
        })
        .catch(err => {
          this.$Message.error({
            content: err.message || err.statusText,
            duration: 5,
            closable: true
          });
          this.$refs[param].resetFields();
          this.form_data.type = "按时间收费";
        })
        .then(() => {
          this.$Spin.hide();
        });
    },

    toIndex() {
      this.isCreate = false;
      this.APILIST(this.search_info);
    },

    /*
		api文档列表请求
		*/
    APIPERMISSIONLIST(id) {
      this.table_loading = true;
      this.axios
        .get(`${window.location.origin}/admin/api/v1/docs?group=face`)
        .then(({ data }) => {
          if (data.code === 200) {
            this.dataList = data.apiDocs;
            this.PermissionList(id); //权限列表请求
            this.PermissionId = id;
          } else {
            throw new Error(data.error);
          }
        })
        .catch(err => {
          this.$Message.error({
            content: err.message || err.statusText,
            duration: 5,
            closable: true
          });
        });
    },

    /*
	 权限请求
	*/
    PermissionList(id) {
      this.axios
        .get(`${window.location.origin}/admin/api/v1/admin/apikey/apigateway`, {
          params: {
            token: this.token,
            apikey_id: id,
            group: "face"
          }
        })
        .then(({ data }) => {
          if (data.code === 200) {
            if (data.gateways.length > 0) {
              for (let index = 0; index < data.gateways.length; index++) {
                for (let count = 0; count < this.dataList.length; count++) {
                  if (index === 0) {
                    this.dataList[count].isChecked = false;
                  }
                  if (
                    this.dataList[count].name === data.gateways[index].endpoint
                  ) {
                    // this.dataList.splice(count, 1);
                    this.dataList[count].isChecked = true;
                  }
                }
              }
            }
            // console.log(this.dataList);

            this.show_permission = true;
          } else if (data.code === 7003) {
            this.$Message.error({
              content: "token验证失败,过期或token错误,请重新登录",
              duration: 5,
              closable: true
            });
            this.$router.push({
              path: "/login"
            });
          } else {
            throw new Error(data.error);
          }
        })
        .catch(err => {
          this.$Message.error({
            content: err.message || err.statusText,
            duration: 5,
            closable: true
          });
        })
        .then(() => {
          this.table_loading = false;
        });
    },

    /**
     * 更新权限
     */
    updatePermission(row) {
      let query_str = {
        token: this.token,
        apikey_id: this.PermissionId,
        group: row.group,
        endpoint: row.name
      };

      if (row.isChecked) {
        query_str.authorize = 0;
      } else {
        query_str.authorize = 1;
      }

      this.table_loading = true;
      this.show_permission = false;

      this.axios
        .post(
          `${window.location.origin}/admin/api/v1/admin/apikey/gateway_status`,
          qs.stringify(query_str)
        )
        .then(({ data }) => {
          if (data.code === 200) {
            this.$Message.success("更新授权成功!");

            this.APILIST(this.search_info);
          } else if (data.code === 7003) {
            this.$Message.error({
              content: "token验证失败,过期或token错误,请重新登录",
              duration: 5,
              closable: true
            });
            this.$router.push({
              path: "/login"
            });
          } else {
            throw new Error(data.error);
          }
        })
        .catch(err => {
          this.$Message.error({
            content: err.message || err.statusText,
            duration: 5,
            closable: true
          });
        })

        .then(() => {
          this.table_loading = false;
        });
    }
  }
};
</script>
